package com.itheima.controller;

import com.alibaba.fastjson.JSON;
import com.itheima.domain.Employee;
import com.itheima.dto.EmployeePostDto;
import com.itheima.dto.LoginDto;
import com.itheima.service.EmployeeService;
import com.itheima.vo.EmployeePageVo;
import com.itheima.vo.LoginVo;
import com.itheima.vo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * date: 2022/5/12 11:10
 *
 * @author daya000
 */
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService service;

    @Autowired(required = false)
    private RedisTemplate redisTemplate;

    @PostMapping("login")
    public Result login(@RequestBody LoginDto dto){
        //将密码通过md5进行加密
        dto.setPassword(getMD5(dto.getPassword()));

        LoginVo login = service.login(dto);

        //判断账号密码是否为空
        if(Objects.isNull(login)){
            return new Result(0,"账号或密码错误",null,null);
        }

        //若登录成功，存储到redis里面
        Employee employee = service.loginRedis(dto);

        //redis的key---token
        String token=UUID.randomUUID().toString().replace("-","");
        // JSON.toJSONString(employee) 实体类转为字符串
        //JSON.parseObject()字符串转为实体类
        redisTemplate.opsForValue().set(token,JSON.toJSONString(employee),7,TimeUnit.DAYS);
        login.setToken(token);
        return new Result(1,null,login,null);
    }

    //md5加密
    public static String getMD5(String str){
        String base=str;
        String md5=DigestUtils.md5DigestAsHex(base.getBytes());
        return md5;
    }
    @PostMapping("")
    public Result addEmployee(@RequestBody EmployeePostDto dto) {
        if (Objects.isNull(dto)) {
            return new Result(0, "参数为空", null, null);
        }
        Employee userName = service.selectByUserName(dto.getUsername());
        if (userName != null) {
            return new Result(0, dto.getName() + "已存在", null, null);
        } else {
            Employee employee = new Employee();
            BeanUtils.copyProperties(dto, employee);
            Boolean result = service.addEmployee(employee);

            Integer code = result ? 1 : 0;
            String msg = result ? "添加成功" : "分类名已存在，添加失败";
            return new Result(code, msg, null, null);
        }

    }



    @PutMapping("")
    public Result updateEmployee(@RequestBody Employee employee) {
        if (Objects.isNull(employee)) {
            return new Result(0, "参数不能为空", null, null);
        }
        Employee entity = new Employee();
        Boolean result = service.updateEmployee(employee);
        int code = result ? 1 : 0;
        String data = result ? "员工信息修改成功" : "员工信息修改失败";
        return new Result(code, null, data, null);
    }

    @GetMapping("/page")
    public Result selectByPage(
            @RequestParam(required = false) String name,
            @RequestParam Integer page,
            @RequestParam Integer pageSize) {
        if (page <= 0) {
            return new Result(0, "页面错误", null, null);
        }
        //获取分页数据
        List<Employee> employeeList = service.selectByPage(name,page, pageSize);
        System.out.println(employeeList);

        //获取总条数
        Long count = service.selectTotal(name);
        EmployeePageVo vo = new EmployeePageVo();
        vo.setRecords(employeeList);
        vo.setTotal(count);
        vo.setSize(pageSize);
        vo.setCurrent(page);
        return new Result(1, null, vo, null);
    }
    @GetMapping("/{id}")
    public Result selectById(@PathVariable String id){
        if (Objects.isNull(id)){
            return new Result(0,"id不能为空",null,null);
        }
        Employee employee = service.selectById(id);
        return new Result(1,null,employee,null);
    }


    @PostMapping("logout")
    public Result logoutController(HttpServletRequest request){
        String token = request.getHeader("Authorization");

        redisTemplate.delete(token);

        Result result = new Result(1,null,"退出成功",null);
        return result;

    }

}
